<template>
  <div id="header">
    <div class="logo">
      <div class="circle">
        <img :src="logo1" alt="" />
      </div>
      <img :src="logo2" alt="" />
    </div>
    <div class="historyAndSearch">
      <div class="history icon-houtui" @click="back"></div>
      <div class="history icon-qianjin" @click="forward"></div>
      <input
        type="text"
        class="search"
        v-model="keyword"
        :placeholder="placeholder"
        @keyup.enter="search"
        @focus="focus"
        @blur="blur"
      />
      <i class="icon-sousuo1" @click="search"></i>
      <div class="popup" v-if="isShowPopup">
        <div v-show="isShowPopup">
          <div id="hot" v-show="isShowHot">
            <div class="titlename">热搜榜</div>
            <ul>
              <li
                v-for="(item, index) in hots"
                :key="index"
                @click="getresult(item.first)"
              >
                <span>{{ index + 1 }}</span
                >{{ item.first }}
              </li>
            </ul>
          </div>
        </div>
        <div id="suggest">
          <div class="titlename" v-show="songs.length">猜你想搜</div>
          <ul>
            <li
              v-for="(item, id) of songs"
              :key="id"
              @click="getresult(item.name)"
            >
              {{ item.name }}-{{ item.artists[0].name }}
            </li>
          </ul>

          <div class="item" v-show="playlists.length">
            <i class="icon-guanbi"></i>歌单
          </div>
          <ul>
            <li
              v-for="(item, id) of playlists"
              :key="id"
              @click="getresult(item.name)"
            >
              {{ item.name }}
            </li>
          </ul>
        </div>
      </div>
    </div>
    <div class="personal">
      <div class="profile">
        <img :src="avatarUrl" alt="" @click="toUserProfile" />
      </div>
      <div class="name" @click="toUserProfile">{{ nickname }}</div>
      <div class="quit" @click="logout">退出登录</div>
    </div>
    <Login
      v-if="isShowLogin"
      :isShowLogin="isShowLogin"
      :changestate="closeLogin"
    ></Login>
  </div>
</template>

<script>
import axios from "axios";
import Login from "./Login.vue";
export default {
  name: "Header",
  components: { Login },
  data() {
    return {
      //引入本地图片
      logo1: require("../assets/logo.png"),
      logo2: require("../assets/logo2.png"),

      isShowLogin: false, //是否展示登录框
      isShowPopup: false, //是否展示搜索提示

      isShowHot: true,
      hots: [],
      placeholder: "suyan",
      keyword: "",

      songs: [],
      playlists: [],
    };
  },
  computed: {
    avatarUrl() {
      return this.$store.state.userAbout.userInfo.avatarUrl;
    },
    nickname() {
      return this.$store.state.userAbout.userInfo.nickname;
    },
    userId() {
      return this.$store.state.userAbout.userInfo.id;
    },
    isLogin(){
      return this.$store.state.userAbout.userInfo.isLogin
    },
  },
  methods: {
    //触发自定义函数，绑定在main组件中，用来控制跳转至个人中心
    //触发函数前先判断是否登录，是——跳转，否——弹出登录框
    toUserProfile() {
      if (this.$store.state.userAbout.userInfo.isLogin) {
        this.$bus.$emit("routeToUserProfile", this.userId);
      } else {
        this.isShowLogin = true;
      }
    },
    //触发自定义函数，绑定在main组件中，用来控制消息列表显示或关闭
    showMessage() {
      this.$bus.$emit("changeShowMessageList");
    },
    //路由回退
    back() {
      this.$router.back();
    },
    //路由前进
    forward() {
      this.$router.forward();
    },
    //关闭登录框
    closeLogin() {
      this.isShowLogin = false;
    },

    //登录异常提示信息
    open3() {
      this.$notify({
        title: "提示",
        message: "登陆异常",
        type: "warning",
        duration: "1500",
      });
    },
    open1() {
      this.$notify({
        title: "退出登录",
        message: "祝您生活愉快",
        type: "success",
        duration: "1500",
      });
    },

    //搜索
    search() {
      let key;
      if (this.keyword == "") {
        key = this.placeholder;
      } else {
        key = this.keyword;
      }
      this.$bus.$emit("ToSearchResult", key);
      this.isShowPopup = false;
    },

    focus() {
      this.isShowPopup = true;
      if (this.keyword == "") {
        this.isShowHot = true;
        this.isShowPopup = true;
      } else {
        this.isShowHot = false;
      }
    },
    blur() {
      setTimeout(() => {
        this.isShowPopup = false;
      }, 300);
    },

    getresult(data) {
      this.$bus.$emit("ToSearchResult", data);
    },

    logout() {
      if(isLogin){
        axios.get("http://localhost:8013/api/login/status").then((res) => {
        this.open1();
        localStorage.removeItem("user");

        //数据传给vuex
        this.$store.commit("userAbout/UPDATEUSERINFO", {
          isLogin: false,
          id: "", //用户id
          avatarUrl: "", //用户头像
          nickname: "", //用户昵称
        });
        setTimeout(() => {
          this.$router.go(0);
        }, 200);
      });
      }
      
    },
  },
  watch: {
    //监控输入框内容，当输入框内容发生变化时，发送请求获得搜索建议
    keyword() {
      axios
        .get(
          "http://localhost:8013/api/search/suggest?keywords=" + this.keyword
        )
        .then((res) => {
          // console.log(res);
          this.songs = res.data.result.songs;
          // console.log(this.songs); //danqu
          this.playlists = res.data.result.playlists;
          // console.log(this.playlists); //gedan
        });
      if (this.keyword == "") {
        // this.songs = []
        // this.artists = []
        // this.playlists = [],
        // this.albums = []
        this.isShowHot = true;
      } else {
        this.isShowHot = false;
      }
    },
  },
  mounted() {
    //挂载后判断是否登录,如果已登录，则刷新登录
    // 如果未登录，查看本地是否存储数据，如果已存储，则取到本地数据调用登录接口
    //如果未存储，·······
    // 想是这么想的，结果不太会调用接口

    if (localStorage.getItem("user")) {
      let acc = JSON.parse(localStorage.getItem("user")).account;
      let pas = JSON.parse(localStorage.getItem("user")).password;
      axios
        .post(
          "http://localhost:8013/api/login/cellphone?phone=" +
            acc +
            "&password=" +
            pas
        )
        .then((res) => {
          //数据传给vuex
          this.$store.commit("userAbout/UPDATEUSERINFO", {
            isLogin: true,
            id: res.data.account.id, //用户id
            avatarUrl: res.data.profile.avatarUrl, //用户头像
            nickname: res.data.profile.nickname, //用户昵称
          });
        })
        .catch(() => {
          this.open3();
        });
    }

    //获取默认搜索词
    axios.get("http://localhost:8013/api/search/default").then((res) => {
      this.placeholder = res.data.data.showKeyword;
    });

    //
    axios.get("http://localhost:8013/api/search/hot").then((res) => {
      this.hots = res.data.result.hots;
    });
  },
};
</script>

<style scoped>
#header {
  text-align: left;
}
#header .logo {
  float: left;
  width: 200px;
  display: flex;
}
#header .logo .circle {
  width: 30px;
  height: 30px;
  position: relative;
  background: #fff;
  border-radius: 50%;
  margin-top: -2px;
}
#header .logo img:nth-child(1) {
  width: 23px;
  height: 23px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
#header .logo img:nth-child(2) {
  width: 112px;
  height: 21px;
  margin-left: 10px;
  margin-top: 4px;
}
.historyAndSearch {
  margin: 15px 0px 0px 300px;
  width: 350px;
  display: flex;
  position: relative;
}
.historyAndSearch .history {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: rgba(160, 160, 160, 0.3);
  margin-right: 15px;
  color: #fff;
  text-align: center;
  line-height: 30px;
  color: rgba(255, 255, 255, 0.4);
}
.historyAndSearch .search {
  width: 250px;
  height: 30px;
  border-radius: 40px;
  background: rgba(160, 160, 160, 0.3);
  outline: none;
  border: none;
  padding: 0px 10px 0 30px;
  font-size: 12px;
  color: #fff;
}
.historyAndSearch .icon-sousuo1 {
  position: absolute;
  top: -15px;
  left: 95px;
  color: #ddd;
}
#header .personal {
  width: 350px;
  float: right;
  margin-right: 30px;
  height: 50px;
  margin-top: -40px;
  line-height: 55px;
  position: relative;
}
#header .personal .profile,
.profile img {
  position: absolute;
  width: 45px;
  height: 45px;
  border-radius: 50%;
  top: 1px;
}
#header .personal .name {
  position: absolute;
  left: 55px;
  color: #fff;
  font-size: 15px;
}
#header .personal .quit {
  position: absolute;
  right: 20px;
  color: #fff;
  cursor: pointer;
}
.popup {
  width: 350px;
  height: 400px;
  overflow: auto;
  box-shadow: 0px 0px 10px rgb(167, 167, 167);
  background: #fff;
  position: absolute;
  top: 60px;
}
.popup .titlename,
.popup .item {
  font-size: 16px;
  color: #aaa;
  height: 50px;
  line-height: 50px;
  background: #fff;
  padding-left: 20px;
}
.popup .titlename,
.popup .item i {
  color: #aaa;
  font-size: 14px;
  padding-right: 5px;
}
.popup ul li {
  height: 50px;
  line-height: 50px;
  padding: 0 20px;
  overflow: hidden;
}
.popup ul li:hover {
  background: #eee;
}
.popup ul li span {
  padding-right: 20px;
  font-weight: 600;
  color: #888;
}
.popup ul li:nth-child(1) span,
.popup ul li:nth-child(2) span,
.popup ul li:nth-child(3) span {
  color: rgb(255, 62, 62);
}

.popup #suggest ul li {
  height: 40px;
  line-height: 40px;
  font-size: 12px;
}
.popup #suggest {
  font-size: 16px;
}
</style>